
from rest_framework import viewsets,status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .models import Vehicle, VehicleImage,VehicleViolation
from .serializers import VehicleSerializer, VehicleImageSerializer,VehicleViolationSerializer
import requests, json
from urllib.parse import quote


class BaiduApi():
    def __init__(self):
        self.API_KEY = "rGClBekW333QWFzF5UxhOXuD"
        self.SECRET_KEY = "Q4vZ9du8BV2TWTiN3BDirWPKULykOCsV"

    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        try:
            response = requests.post(url, params=params)
            response.raise_for_status()
            return str(response.json().get("access_token"))
        except requests.RequestException as e:
            raise Exception(f"获取百度API访问令牌失败: {str(e)}")

    def license_plate(self, picurl):
        """
        车牌识别
        :param picurl: 图片URL
        :return: 识别结果
        """
        try:
            # 确保URL格式正确，添加协议前缀（如果缺失）
            if not picurl.startswith(('http://', 'https://')):
                picurl = 'http://' + picurl

            # 对URL进行编码处理，解决中文字符问题
            encoded_url = quote(picurl, safe='')
            access_token = self.get_access_token()
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + access_token

            payload = 'url=%s' % (encoded_url)
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            }

            response = requests.request("POST", url, headers=headers, data=payload)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            return {"error": f"车牌识别请求失败: {str(e)}"}
        except json.JSONDecodeError as e:
            return {"error": f"车牌识别响应解析失败: {str(e)}"}

    # 文字识别
    def fontmessage(self, picurl):
        try:
            # 确保URL格式正确，添加协议前缀（如果缺失）
            if not picurl.startswith(('http://', 'https://')):
                picurl = 'http://' + picurl

            # 对URL进行编码处理，解决中文字符问题
            encoded_url = quote(picurl, safe='')
            access_token = self.get_access_token()
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + access_token

            payload = 'url=%s&detect_direction=false&paragraph=false&probability=false' % (encoded_url)
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            }
            response = requests.request("POST", url, headers=headers, data=payload)
            response.raise_for_status()
            data = response.json()

            # 检查是否有识别结果
            if 'words_result' in data and len(data['words_result']) > 0:
                # 返回所有识别到的文字，而不仅仅是前两个
                words_list = [item['words'] for item in data['words_result']]
                return {"words_list": words_list}
            return {"words_list": []}
        except requests.RequestException as e:
            return {"error": f"文字识别请求失败: {str(e)}"}
        except (json.JSONDecodeError, KeyError) as e:
            return {"error": f"文字识别解析失败: {str(e)}"}

    # 车辆识别（用于识别车型和车辆颜色）
    def car_identify(self, picurl):
        """
        车辆识别，识别车型和车辆颜色
        :param picurl: 图片URL
        :return: 识别结果
        """
        try:
            # 确保URL格式正确，添加协议前缀（如果缺失）
            if not picurl.startswith(('http://', 'https://')):
                picurl = 'http://' + picurl

            access_token = self.get_access_token()
            url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car?access_token=" + access_token

            payload = 'url=%s&output_brand=false' % (quote(picurl, safe=''))
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            }

            response = requests.request("POST", url, headers=headers, data=payload)
            response.raise_for_status()
            return response.json()
        except requests.RequestException as e:
            return {"error": f"车辆识别请求失败: {str(e)}"}
        except json.JSONDecodeError as e:
            return {"error": f"车辆识别响应解析失败: {str(e)}"}


class VehicleRecognizeView(APIView):
    """
    车辆信息识别接口（仅识别，不保存到数据库）
    """

    def post(self, request):

        # 获取图片URL和用户ID
        image_url = request.data.get('img_url')
        user_id = request.data.get('user_id')

        print("接收到的数据:", request.data)
        print("图片URL:", image_url)
        print("用户ID:", user_id)

        if not image_url or not user_id:
            return Response({"error": "缺少图片URL或用户ID"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 2. 百度智能云车牌识别
            baidu_api = BaiduApi()
            plate_result = baidu_api.license_plate(image_url)

            if "error" in plate_result:
                return Response({"error": "车牌识别失败", "details": plate_result["error"]},
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            plate_number = ''
            plate_color = ''
            if plate_result.get('words_result'):
                plate_number = plate_result['words_result'].get('number', '')
                plate_color = plate_result['words_result'].get('color', '')

            # 3. 通用OCR识别其它文字
            ocr_result = baidu_api.fontmessage(image_url)

            if "error" in ocr_result:
                # 即使OCR识别失败也继续处理，因为不是关键信息
                ocr_result = {"words_list": []}

            # 4. 车辆识别（获取车型和车辆颜色）
            car_result = baidu_api.car_identify(image_url)
            vehicle_color = ''
            vehicle_model = ''

            if "error" not in car_result:
                # 获取车辆颜色和车型信息
                vehicle_color = car_result.get('color_result', '')
                vehicle_model = car_result.get('result', [{}])[0].get('name', '') if car_result.get('result') else ''

            # 5. 返回识别结果（不保存到数据库）
            return Response({
                "recognition_data": {
                    "plate_number": plate_number,
                    "plate_color": plate_color,
                    "vehicle_model": vehicle_model,
                    "vehicle_color": vehicle_color,
                    "image_url": image_url
                },
                "plate_result": plate_result,
                "ocr_result": ocr_result,
                "car_result": car_result
            }, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({"error": f"处理车辆信息时发生错误: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VehicleSubmitView(APIView):
    """
    车辆信息提交接口（保存到数据库）
    """

    def post(self, request):
        # 获取提交的车辆信息
        user_id = request.data.get('user_id')
        plate_number = request.data.get('plate_number')
        model = request.data.get('model')
        color = request.data.get('color')
        image_url = request.data.get('image_url')

        print("提交的车辆信息:", request.data)

        if not all([user_id, plate_number, model, color, image_url]):
            return Response({"error": "缺少必要的车辆信息"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 检查车牌号是否已存在
            if Vehicle.objects.filter(plate_number=plate_number).exists():
                return Response({"error": "该车牌号已存在"}, status=status.HTTP_400_BAD_REQUEST)

            # 保存车辆信息到数据库
            vehicle = Vehicle.objects.create(
                user_id=user_id,
                plate_number=plate_number,
                model=model,
                color=color,
                status=0  # 待审核状态
            )

            # 保存车辆图片
            vehicle_image = VehicleImage.objects.create(
                vehicle=vehicle,
                image_url=image_url,
                audit_status=0  # 待审核状态
            )

            return Response({
                "message": "车辆信息提交成功，请等待审核",
                "vehicle": VehicleSerializer(vehicle).data,
                "vehicle_image": VehicleImageSerializer(vehicle_image).data
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response({"error": f"保存车辆信息时发生错误: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VehicleImageAuditView(APIView):
    """
    车辆图片审核（审核状态）
    """
    def post(self, request, pk):
        try:
            vehicle_image = VehicleImage.objects.get(pk=pk)
        except VehicleImage.DoesNotExist:
            return Response({"error": "未找到图片"}, status=status.HTTP_404_NOT_FOUND)

        audit_status = request.data.get("audit_status")
        if audit_status not in [0, 1, 2]:
            return Response({"error": "审核状态不合法"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            vehicle_image.audit_status = audit_status
            vehicle_image.save()
            return Response({"msg": "审核成功", "audit_status": audit_status})
        except Exception as e:
            return Response({"error": f"审核状态保存失败: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VehicleAuditView(APIView):
    """
    车辆审核接口（修改车辆状态）
    """

    def post(self, request, pk):
        try:
            vehicle = Vehicle.objects.get(pk=pk)
        except Vehicle.DoesNotExist:
            return Response({"error": "未找到车辆"}, status=status.HTTP_404_NOT_FOUND)

        # 获取请求参数
        vehicle_status = request.data.get("vehicle_status")

        # 验证参数
        if vehicle_status is None:
            return Response({"error": "缺少车辆状态参数"}, status=status.HTTP_400_BAD_REQUEST)

        if vehicle_status not in [0, 1]:
            return Response({"error": "车辆状态值不合法，只能为0(正常)或1(禁用)"},
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            # 更新车辆状态
            vehicle.status = vehicle_status
            vehicle.save()

            return Response({
                "msg": "审核成功",
                "vehicle": VehicleSerializer(vehicle).data,
                "vehicle_status": vehicle_status
            })
        except Exception as e:
            return Response({"error": f"审核失败: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VehicleViewSet(ModelViewSet):
    """
    车辆管理ViewSet - 提供完整的CRUD操作
    """
    queryset = Vehicle.objects.all()
    serializer_class = VehicleSerializer

    def get_queryset(self):
        """根据用户ID过滤车辆"""
        queryset = Vehicle.objects.all()
        user_id = self.request.query_params.get('user_id', None)
        if user_id is not None:
            queryset = queryset.filter(user_id=user_id)
        return queryset.order_by('-created_at')

    def list(self, request, *args, **kwargs):
        """获取车辆列表"""
        try:
            queryset = self.get_queryset()
            serializer = self.get_serializer(queryset, many=True)

            # 为每个车辆添加图片信息
            vehicles_data = []
            for vehicle_data in serializer.data:
                vehicle = Vehicle.objects.get(id=vehicle_data['id'])
                # 获取第一张图片作为展示图片
                first_image = VehicleImage.objects.filter(vehicle=vehicle).first()
                vehicle_data['image_url'] = first_image.image_url if first_image else None
                vehicles_data.append(vehicle_data)

            return Response(vehicles_data)
        except Exception as e:
            return Response({"error": f"获取车辆列表失败: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def retrieve(self, request, *args, **kwargs):
        """获取车辆详情"""
        try:
            vehicle = self.get_object()
            serializer = self.get_serializer(vehicle)
            vehicle_data = serializer.data

            # 添加车辆图片信息
            images = VehicleImage.objects.filter(vehicle=vehicle)
            vehicle_data['images'] = VehicleImageSerializer(images, many=True).data

            return Response(vehicle_data)
        except Exception as e:
            return Response({"error": f"获取车辆详情失败: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def update(self, request, *args, **kwargs):
        """更新车辆信息"""
        try:
            partial = kwargs.pop('partial', False)
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            return Response(serializer.data)
        except Exception as e:
            return Response({"error": f"更新车辆信息失败: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def destroy(self, request, *args, **kwargs):
        """删除车辆"""
        try:
            instance = self.get_object()
            # 同时删除相关的车辆图片
            VehicleImage.objects.filter(vehicle=instance).delete()
            self.perform_destroy(instance)
            return Response({"message": "车辆删除成功"}, status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            return Response({"error": f"删除车辆失败: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class VehicleImageViewSet(ModelViewSet):
    """
    车辆图片管理ViewSet
    """
    queryset = VehicleImage.objects.all()
    serializer_class = VehicleImageSerializer

    def get_queryset(self):
        """根据车辆ID过滤图片"""
        queryset = VehicleImage.objects.all()
        vehicle_id = self.request.query_params.get('vehicle_id', None)
        print(f"获取车辆图片，vehicle_id参数: {vehicle_id}")
        print(f"所有查询参数: {self.request.query_params}")
        if vehicle_id is not None:
            queryset = queryset.filter(vehicle_id=vehicle_id)
            print(f"过滤后的图片数量: {queryset.count()}")
        return queryset.order_by('-created_at')

    def list(self, request, *args, **kwargs):
        """获取车辆图片列表"""
        try:
            queryset = self.get_queryset()
            serializer = self.get_serializer(queryset, many=True)
            return Response(serializer.data)
        except Exception as e:
            return Response({"error": f"获取车辆图片失败: {str(e)}"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class VehicleViolationViewSet(viewsets.ModelViewSet):
    queryset = VehicleViolation.objects.all()
    serializer_class = VehicleViolationSerializer
    lookup_url_kwarg = 'pk'
    lookup_field = 'pk'